package com.example.my_bookkeeping.ui.category;

import android.annotation.SuppressLint;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.text.TextUtils;

import com.example.my_bookkeeping.R;
import com.example.my_bookkeeping.data.manager.CategoryManager;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;

public class CategoryFragment extends Fragment implements CategoryManager.Observer{

    private final CategoryManager categoryManager = CategoryManager.getInstance();
    private CategoryAdapter categoryAdapter;
    private TabLayout tabLayout;

    public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.CategoryViewHolder> {

        private ArrayList<String> categoryList;
        private final CategoryFragment fragment;

        public CategoryAdapter(ArrayList<String> categoryList) {
            this.categoryList = categoryList;
            this.fragment = CategoryFragment.this;
        }

        @SuppressLint("NotifyDataSetChanged")
        public void setCategoryList(ArrayList<String> categoryList) {
            this.categoryList = categoryList;
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public CategoryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_category, parent, false);
            return new CategoryViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull CategoryViewHolder holder, int position) {
            holder.tvCategory.setText(categoryList.get(position));
            holder.btnEdit.setOnClickListener(v -> fragment.showEditDialog(categoryList.get(position), false));
            holder.btnDelete.setOnClickListener(v -> {
                // 显示确认删除对话框
                new AlertDialog.Builder(v.getContext())
                    .setTitle(R.string.category_dialog_title_delete_category)
                    .setMessage(R.string.category_dialog_message_delete_category)
                    .setPositiveButton(R.string.category_button_confirm, (dialog, which) -> {
                        // 获取当前分类名称
                        String category = categoryList.get(position);
                        // 根据当前选中的Tab判断是收入还是支出分类
                        boolean isIncome = tabLayout.getSelectedTabPosition() == 1;
                        // 删除分类
                        categoryManager.deleteCategory(category, isIncome);
                    })
                    .setNegativeButton(R.string.category_button_cancel, null)
                    .show();
            });
        }

        @Override
        public int getItemCount() {
            return categoryList.size();
        }

        // 这里设置每个item的显示样式，已经实现了视图资源的绑定
        public class CategoryViewHolder extends RecyclerView.ViewHolder {
            TextView tvCategory;
            ImageButton btnEdit;
            ImageButton btnDelete;

            public CategoryViewHolder(@NonNull View itemView) {
                super(itemView);
                tvCategory = itemView.findViewById(R.id.tv_category);
                btnEdit = itemView.findViewById(R.id.btn_edit);
                btnDelete = itemView.findViewById(R.id.btn_delete);
            }
        }
    }

    @Override
    public void update() {
        // 更新RecyclerView显示
        if (tabLayout.getSelectedTabPosition() == 0) {
            categoryAdapter.setCategoryList(categoryManager.getExpenseCategoryList());
        } else {
            categoryAdapter.setCategoryList(categoryManager.getIncomeCategoryList());
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_category, container, false);

        // 设置添加分类的按钮，弹出对话框，让用户输入分类名称
        rootView.findViewById(R.id.button_add_category).setOnClickListener(v -> showEditDialog("", true));

        // 设置RecyclerView
        RecyclerView recyclerView = rootView.findViewById(R.id.recyclerView_category);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        // 设置TabLayout，切换收入和支出分类
        tabLayout = rootView.findViewById(R.id.tab_book_keep_type);
        categoryAdapter = new CategoryAdapter(categoryManager.getExpenseCategoryList());
        recyclerView.setAdapter(categoryAdapter);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    categoryAdapter.setCategoryList(categoryManager.getExpenseCategoryList());
                } else {
                    categoryAdapter.setCategoryList(categoryManager.getIncomeCategoryList());
                }
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

        // 注册观察者
        categoryManager.addObserver(this);

        return rootView;
    }

    private void showEditDialog(String categoryName, boolean isAdd) {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_category, null);

        EditText etName = dialogView.findViewById(R.id.et_category_name);
        RadioGroup radioGroupType = dialogView.findViewById(R.id.rg_category_type);

        // 设置当前值和类型
        if (!isAdd) {
            etName.setText(categoryName);
            etName.setSelection(categoryName.length());
            boolean isIncome = categoryManager.isIncomeCategory(categoryName);
            radioGroupType.check(isIncome ? R.id.rb_income : R.id.rb_expense);
        }

        builder.setView(dialogView)
                .setTitle(isAdd ? R.string.category_dialog_title_add_category : R.string.category_dialog_title_edit)
                .setPositiveButton(R.string.category_button_confirm, null)
                .setNegativeButton(R.string.category_button_cancel, null);

        AlertDialog dialog = builder.create();
        dialog.show();

        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> {
            String newName = etName.getText().toString().trim();

            if (TextUtils.isEmpty(newName)) {
                Toast.makeText(requireContext(), R.string.category_error_empty_name, Toast.LENGTH_SHORT).show();
                return;
            }

            // 获取用户选择的分类类型（收入/支出）
            int selectedId = radioGroupType.getCheckedRadioButtonId();
            boolean newIsIncome = selectedId == R.id.rb_income;
            if (isAdd) {
                // 调用 CategoryManager 类的新增方法添加分类
                boolean isAdded;
                if (newIsIncome) {
                    isAdded = categoryManager.addIncomeCategory(newName);
                } else {
                    isAdded = categoryManager.addExpenseCategory(newName);
                }
                // 提示添加结果
                if (!isAdded)
                    Toast.makeText(requireContext(), "分类已存在", Toast.LENGTH_SHORT).show();
            } else {
                // 更新分类名称
                categoryManager.updateCategory(categoryName, newName);
                // 更新分类类型
                categoryManager.moveCategory(newName, newIsIncome);
            }
            dialog.dismiss();
        });
    }
}